package com.components.cachewebview.utils

import android.text.TextUtils
import android.util.Log
import com.tencent.smtt.sdk.MimeTypeMap
import java.util.*

object MimeTypeMapUtils {

     fun getFileExtensionFromUrl(url: String): String {
        var lowercase = url.lowercase(Locale.getDefault())
        if (!TextUtils.isEmpty(lowercase)) {
            val fragment = lowercase.lastIndexOf('#')
            if (fragment > 0) {
                lowercase = lowercase.substring(0, fragment)
            }
            val query = lowercase.lastIndexOf('?')
            if (query > 0) {
                lowercase = lowercase.substring(0, query)
            }
            val fileNamePos = lowercase.lastIndexOf('/')
            val fileName = if (0 <= fileNamePos) lowercase.substring(fileNamePos + 1) else lowercase
            if (fileName.isNotEmpty()) {
                val dotPos = fileName.lastIndexOf('.')
                if (0 <= dotPos) {
                    return fileName.substring(dotPos + 1)
                }
            }
        }
        return ""
    }

    fun getMimeTypeFromUrl(url: String): String? {
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileExtensionFromUrl(url))
    }

}